#include "my_can.h"

void can_pack_frame(uint8_t* buffer, const void* frame, size_t size)
{
  memcpy(buffer, frame, size - 1);
  buffer[size - 1] = crc8_ccitt(buffer, size - 1);
}

bool can_unpack_frame(void* frame, const uint8_t* buffer, size_t size)
{
  uint8_t crc = crc8_ccitt(buffer, size - 1);
  if (crc != buffer[size - 1])
  {
    return false; // CRC 校验失败
  }
  memcpy(frame, buffer, size);
  return true;    // 解包成功
}

void process_can_message(FDCAN_MessageTypeDef* message)
{
  if (message == NULL)
  {
    return;   // 无效输入
  }

  uint8_t frame_type = message->RxData[0];    // 获取帧头
  
  printf("frame_type 0x%02X\n", frame_type);

  switch (frame_type)
  {
  case CAN_FRAME_TYPE_INIT:               // 接收到初始化帧
    handle_init_frame(message);
    break;
  case CAN_FRAME_TYPE_TARGET_POSITION:    // 接收到目标位置帧
    handle_target_position_frame(message);
    break;
  case CAN_FRAME_TYPE_TARGET_TORQUE:      // 接收到目标力矩帧
    handle_target_torque_frame(message);
    break;
  case CAN_FRAME_TYPE_STATUS:             // 接收到状态帧
    handle_status_frame(message);
    break;
  case CAN_FRAME_TYPE_POSITION:           // 接收到实时位置帧
    handle_position_frame(message);
    break;
  case CAN_FRAME_TYPE_ELECTRIC_ANGLE:     // 接收到电角度帧
    handle_electric_angle_frame(message);
    break;
  case CAN_FRAME_TYPE_VD:                 // 接收到Vd帧
    handle_vd_frame(message);
    break;
  case CAN_FRAME_TYPE_IQ:                 // 接收到Iq帧
    handle_iq_frame(message);
    break;
  case CAN_FRAME_TYPE_QUERY:              // 接收到查询帧
    handle_query_frame(message);
    break;
  default:
    break;
  }

}
